package com.szzg10.thinking.chapter18;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Serializer;

public class Person {

	public static final String FILE_XML = "C:/Users/ZhongGe/Desktop/person.xml";
	
	private String first;
	private String last;
	
	public Person(String first, String last) {
		this.first = first;
		this.last = last;
	}
	
	public Person(Element element) {
		first = element.getFirstChildElement("first").getValue();
		last = element.getFirstChildElement("last").getValue();
	}
	
	public static void main(String[] args) throws IOException {
		List<Person> list = new ArrayList<Person>();
		list.add(new Person("Peter", "Zhang"));
		list.add(new Person("Anne", "Chen"));
		list.add(new Person("Sue", "Li"));
		
		Element root = new Element("people");
		for(Person person: list) {
			root.appendChild(person.getXML());
		}
		
		Document document = new Document(root);
		
		File file = new File(FILE_XML);
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		
		format(fileOutputStream, document);
	}
	
	public Element getXML() {
		Element person = new Element("person");
		
		Element first = new Element("first");
		first.appendChild(this.first);
		Element last = new Element("last");
		last.appendChild(this.last);
		
		person.appendChild(first);
		person.appendChild(last);
		
		return person;
	}
	
	@Override
	public String toString() {
		return first + " " + last;
	}
	
	public static void format(OutputStream outputStream, Document document) throws IOException {
		Serializer serializer = new Serializer(outputStream, "ISO-8859-1");
		serializer.setIndent(4);
		serializer.setMaxLength(60);
		serializer.write(document);
		serializer.flush();
	}

	//---getter and setter---
	public String getFirst() {
		return first;
	}

	public String getLast() {
		return last;
	}

	public void setFirst(String first) {
		this.first = first;
	}

	public void setLast(String last) {
		this.last = last;
	}
	
}
